'use strict'

const EventEmitter3 = require('eventemitter3');
const Centrifuge = require('centrifuge');

const logger = require('./logger')('Ws');

let _websocketInstance = null;

/**
 * websocket
 */
class Ws extends EventEmitter3 {
  constructor(config) {
    super();
    this._centrifuge = new Centrifuge({
      url: config.url,
      user: config.user,
      timestamp: config.timestamp,
      info: config.info,
      token: config.token
    });
    this.peerId = config.user;
    this._url = config.url;
    this._user = config.user;
    this.channelPrefix = config.channel;
    this._connect();
  }

  static Singleton(config) {
    if (!_websocketInstance) {
      _websocketInstance = new Ws(config);
    }
    return _websocketInstance;
  }

  _connect() {
    logger.info(`url=${this._url}`);
    logger.info(`user=${this._user}`);

    this._centrifuge.on('error', err => {
      logger.error(err);
      // this.emit('error', err);
    })
    this._centrifuge.connect()
  }

  subscribe(channel, events) {
    // logger.info('subscibe:', channel, events);
    return this._centrifuge.subscribe(channel, events);
  }
}

module.exports = Ws.Singleton;
module.exports.Ws = Ws;
